package com.cnap.multiclouldmgmt.scheduleTask;


import com.alibaba.fastjson.JSON;
import com.cnap.multiclouldmgmt.model.flavor.CloudFlavorInfo;
import com.cnap.multiclouldmgmt.model.flavor.DiskTypeInfo;
import com.cnap.multiclouldmgmt.model.flavor.FlavorInfo;
import com.cnap.multiclouldmgmt.model.flavor.ImageInfo;
import com.cnap.multiclouldmgmt.model.gpu.FlavorGPUInfoWithImageDisk;
import com.cnap.multiclouldmgmt.model.gpu.GpuFlavorInfo;
import com.cnap.multiclouldmgmt.model.gpu.GpuSpecInfo;
import com.cnap.multiclouldmgmt.model.k8sModels.SvcModel;
import com.cnap.multiclouldmgmt.repository.master.FlavorInfoMapper;
import com.cnap.multiclouldmgmt.repository.master.K8sClusterEventsMapper;
import com.cnap.multiclouldmgmt.service.CacheService;
import com.cnap.multiclouldmgmt.service.MicroSvcInfoService;
import com.cnap.multiclouldmgmt.service.MultiCloudMgmtService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author dyq
 * 清理超过两周的events
 */
@Configuration
@EnableScheduling
public class CleanK8sEventsScheduledTask {

    private final static Logger LOGGER = LoggerFactory.getLogger(CleanK8sEventsScheduledTask.class);

    @Autowired
    private K8sClusterEventsMapper k8sClusterEventsMapper;

    @Autowired
    private MultiCloudMgmtService multiCloudMgmtService;



    @Autowired
    private CacheService cacheService;

    private static final String VM_CONTROLER_URL = "http://cnap-cloud-mgmt-be-svc.default.svc.cluster.local:8080";

    @Autowired
    private MicroSvcInfoService microSvcInfoService;


    //每小时清理一次
    @Scheduled(fixedDelay = 6*60*60*1000)
    public void cleanEvents() {

        try{
            //检查是否开始处理
            if (LOGGER.isInfoEnabled()){
                LOGGER.error("CleanK8sEventsScheduledTask cleanEvents begin");
            }

            //通知其他集群
            multiCloudMgmtService.informOtherSvcClusterChange();
            //删除超过15天的事件
            k8sClusterEventsMapper.delEventsByTime(LocalDateTime.now().minus( 15, ChronoUnit.DAYS));

            //获取所有的svcId,用于update_indicator
            List<SvcModel> svcModels  = cacheService.getSvcModelsForMicroSvc();
            Set<String> svcIds = new HashSet<>();
            for (SvcModel svcModel:svcModels){
                svcIds.add(svcModel.getMicroSvcId());
            }
            for (String svcId:svcIds) {
                microSvcInfoService.getAndSaveMicroSvcHistoryModel(svcId);
            }

        }catch(Exception e){
          LOGGER.error("CleanK8sEventsScheduledTask cleanEvents error",e);
        }
    }

    /**
     *
     * @param url
     * @return
     */
    private String doHttpGetReq(String url){

        try {

            CloseableHttpClient httpclient = HttpClients.createDefault();

            HttpGet httpGet = new HttpGet(url);

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5 * 60 * 1000).setConnectionRequestTimeout(5 * 60 * 1000)
                    .setSocketTimeout(5 * 60 * 1000).build();
            httpGet.setConfig(requestConfig);

            CloseableHttpResponse response = httpclient.execute(httpGet);
            return EntityUtils.toString(response.getEntity());

        }catch (Throwable e){
            LOGGER.error("CleanK8sEventsScheduledTask doHttpGetReq fail url={}",url,e);
        }

        return null;
    }
    
}
